<ul class="nav nav-tabs">
    <li class="active"><a href="#info" data-toggle="tab">{{ _("Info") }}</a></li>
    <li class="hide"><a href="#plans" data-toggle="tab">{{ _("Plans") }}</a></li>
    <li class="hide"><a href="#history" data-toggle="tab">{{ _("History") }}</a></li>
    <li class="hide"><a href="#help" data-toggle="tab">{{ _("Help") }}</a></li>
</ul>
<div class="tab-content">
    <div id="info" class="tab-pane fade in active">
        <form id="login-form" onSubmit="onLoginSubmit(); return false;">
            <h4>{{ _("Login") }}</h4>
            <p>
                <label for="login-username">{{ _("Email") }}</label>
                <input id="login-username" type="text" />
            </p>
            <p>
                <label for="login-password">{{ _("Password") }}</label>
                <input id="login-password" type="password" />
            </p>
            <p>
                <button class="btn btn-primary btn-block" type="submit">{{ _("Login") }}</button>
            </p>
            <p class="text-center">
                <a id="register-trigger" href="javascript:void(0);">{{ _("Haven't an account?") }}</a>
            </p>
        </form> <!-- #login-form -->
        <form id="register-form" class="hide" onSubmit="onRegisterSubmit(); return false;">
            <h4>{{ _("Register") }}</h4>
            <p>
                <label for="register-username">{{ _("Email") }}</label>
                <input id="register-username" type="text" />
            </p>
            <p>
                <label for="register-password">{{ _("Password") }}</label>
                <input id="register-password" type="password" />
            </p>
            <p>
                <button class="btn btn-primary btn-block" type="submit">{{ _("Register") }}</button>
            </p>
            <p class="text-center">
                <a id="login-trigger" href="javascript:void(0);">{{ _("Already have an account?") }}</a>
            </p>
        </form> <!-- #register-form -->
        <div id="account-information" class="hide">
            <div class="section">
                <h4>{{ _("Summary") }}</h4>
                <div class="row-fluid">
                    <div class="span4">
                        <label for="login-account">{{ _("Account") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span8">
                        <p>
                            <span id="login-account">N/a</span>
                            <a id="logout-trigger" href="javascript:void(0)">[{{ _("Logout") }}]</a>
                        </p>
                    </div> <!-- .span8 -->
                </div> <!-- .row-fluid -->
                <div class="row-fluid">
                    <div class="span4">
                        <label for="credit">{{ _("Credit") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span8">
                        <p>
                            <span id="credit">N/a</span>
                            <a id="charge-trigger" href="javascript:void(0);">[{{ _("Charge") }}]</a>
                            <a id="transfer-credit-trigger" href="javascript:void(0);">[{{ _("Transfer") }}]</a>
                        </p>
                    </div> <!-- .span8 -->
                </div> <!-- .row-fluid -->
                <div class="row-fluid">
                    <div class="span4">
                        <label for="bandwidth">{{ _("Bandwidth") }}</label>
                    </div> <!-- .span4 -->
                    <div class="span8">
                        <p>
                            <span id="bandwidth">N/a</span>
                        </p>
                    </div> <!-- .span8 -->
                </div> <!-- .row-fluid -->
            </div> <!-- .section -->
            <div class="section">
                <h4>{{ _("Available Bandwidth") }}</h4>
                <p id="no-bandwidth">{{ _("No bandwidth available.") }}</p>
                <table id="available-bandwidth" class="table hide">
                    <thead>
                        <tr>
                            <th>{{ _("Expire Time") }}</th>
                            <th>{{ _("Left Bandwidth") }}</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div> <!-- .section -->
        </div> <!-- #account-information -->
    </div> <!-- #info -->
    <div id="plans" class="tab-pane fade in">
        <div class="section">
            <h4>{{ _("Plans and Pricing") }}</h4>
            <div class="row-fluid">
                <ul class="thumbnails">
                    <li class="span4">
                        <div class="thumbnail">
                            <div class="caption">
                                <h1 class="price"><sup>$</sup> 4.5</h1>
                                <ul class="details">
                                    <li>
                                        <div class="row-fluid">
                                            <div class="span4 text-right">300</div> <!-- .span4 -->
                                            <div class="span8">GB {{ _("Bandwidth") }}</div> <!-- .span8 -->
                                        </div> <!-- .row-fluid -->
                                    </li>
                                    <li>
                                        <div class="row-fluid">
                                            <div class="span4 text-right">3</div> <!-- .span4 -->
                                            <div class="span8">{{ _("Months") }}</div> <!-- .span8 -->
                                        </div> <!-- .row-fluid -->
                                    </li>
                                </ul>
                                <p>
                                    <a href="javascript:void(0);" id="quarterly-plan-trigger" class="btn btn-primary btn-block">{{ _("Buy Now") }}</a>
                                </p>
                            </div> <!-- .caption -->
                        </div> <!-- .thumbnail -->
                    </li>
                    <li class="span4">
                        <div class="thumbnail">
                            <div class="caption">
                                <h1 class="price"><sup>$</sup> 15</h1>
                                <ul class="details">
                                    <li>
                                        <div class="row-fluid">
                                            <div class="span4 text-right">1200</div> <!-- .span4 -->
                                            <div class="span8">GB {{ _("Bandwidth") }}</div> <!-- .span8 -->
                                        </div> <!-- .row-fluid -->
                                    </li>
                                    <li>
                                        <div class="row-fluid">
                                            <div class="span4 text-right">12</div> <!-- .span4 -->
                                            <div class="span8">{{ _("Months") }}</div> <!-- .span8 -->
                                        </div> <!-- .row-fluid -->
                                    </li>
                                </ul>
                                <p>
                                    <a href="javascript:void(0);" id="yearly-plan-trigger" class="btn btn-primary btn-block">{{ _("Buy Now") }}</a>
                                </p>
                            </div> <!-- .caption -->
                        </div> <!-- .thumbnail -->
                    </li>
                </ul>
            </div> <!-- .row-fluid -->
        </div> <!-- .section -->
        <div class="section" hidden>
            <h4>{{ _("Billing History") }}</h4>
            <p id="no-billing-history">{{ _("No billing history.") }}</p>
            <table id="billing-history" class="table hide">
                <thead>
                    <tr>
                        <th>{{ _("Time") }}</th>
                        <th>{{ _("Description") }}</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div> <!-- .section -->
    </div> <!-- #plans -->
    <div id="history" class="tab-pane fade in">
        <div class="row-fluid">
            <div class="span6">
                <h4>{{ _("History") }}</h4>
            </div> <!-- .span6 -->
            <div class="span6 text-right">
                <button class="btn btn-primary" id="get-history-button">{{ _("Get") }}</button>
            </div> <!-- .span6 -->
        </div> <!-- .row-fluid -->
        <table id="history-list" class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th >{{ _("Time") }}</th>
                    <th>{{ _("Action") }}</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div> <!-- #history -->
    <div id="help" class="tab-pane fade in">
        <h4>{{ _("Help") }}</h4>
        <div class="row-fluid">
            <div class="span4">
                <label>Socks5</label>
            </div> <!-- .span4 -->
            <div class="span8">
                <p>127.0.0.1:1080</p>
            </div> <!-- .span8 -->
        </div> <!-- .row-fluid -->
        <div class="row-fluid">
            <div class="span4">
                <label>Wiki</label>
            </div> <!-- .span4 -->
            <div class="span8">
                <p><a href="https://github.com/XX-net/XX-Net/wiki/x-tunnel%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B" target="_blank">X-Tunnel Wiki@GitHub</a></p>
            </div> <!-- .span8 -->
        </div> <!-- .row-fluid -->
    </div> <!-- #help -->
</div> <!-- #tab-content -->

<!-- Modals -->
<form id="charge-modal" class="modal hide fade" action="https://www.paypal.com/cgi-bin/webscr" method="POST" target="_blank">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h5>{{ _("Charge") }}</h5>
    </div> <!-- .modal-header -->
    <div class="modal-body">
        <div class="alert alert-warning hide">{{ _("You haven't enough credit. Please charge first.") }}</div> <!-- .alert-warning -->
        <!-- Plan Field -->
        <input type="hidden" name="on0" value="Plan">
        <label for="charge-plan">{{ _("Plan") }}:</label>
        <select id="charge-plan" name="os0">
            <option value="Quarterly">{{ _("Quarterly") }} $4.50</option>
            <option value="Yearly">{{ _("Yearly") }} $15.00</option>
        </select> 
        <!-- Account Field -->
        <input type="hidden" name="on1" value="account">
        <input class="login-account" type="hidden" name="os1">
    </div> <!-- .modal-body -->
    <div class="modal-footer">
        <input type="hidden" name="cmd" value="_s-xclick">
        <input type="hidden" name="hosted_button_id" value="WBX5H8PS54N22">
        <input type="hidden" name="currency_code" value="USD">
        <a href="javascript:void(0);" class="btn" data-dismiss="modal">{{ _("Close") }}</a>
        <button class="btn btn-primary">{{ _("Buy Now") }}</button>
    </div> <!-- .modal-footer -->
</form> <!-- #charge-modal -->

<div id="transfer-credit-modal" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h5>{{ _("Transfer Credit") }}</h5>
    </div> <!-- .modal-header -->
    <div class="modal-body">
        <div class="alert alert-error hide"></div> <!-- .alert-error -->
        <p>
            <label for="transfer-credit-username">{{ _("Username transfer to") }}</label>
            <input id="transfer-credit-username" type="text" placeholder="{{ _("Email Address") }}" />
        </p>
        <p>
            <label for="transfer-credit-amount">{{ _("Credit to transfer") }} (<strong>USD</strong>)</label>
            <input id="transfer-credit-amount" type="text" value="0" onkeyup="isDecimalNumber(this)" />
        </p>
    </div> <!-- .modal-body -->
    <div class="modal-footer">
        <a href="javascript:void(0);" class="btn" data-dismiss="modal">{{ _("Close") }}</a>
        <button class="btn btn-primary">{{ _("Transfer") }}</button>
    </div> <!-- .modal-footer -->
</div> <!-- #transfer-credit-modal -->

<div id="transfer-bandwidth-modal" class="modal hide fade">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h5>{{ _("Transfer Bandwidth") }}</h5>
    </div> <!-- .modal-header -->
    <div class="modal-body">
        <div class="alert alert-error hide"></div> <!-- .alert-error -->
        <p>
            <label for="transfer-bandwidth-username">{{ _("Username transfer to") }}</label>
            <input id="transfer-bandwidth-username" type="text" placeholder="{{ _("Email Address") }}" />
        </p>
        <p>
            <label for="transfer-bandwidth-amount">{{ _("Bandwidth to transfer") }} (<strong>MB</strong>)</label>
            <input id="transfer-bandwidth-amount" type="text" onkeyup="isDecimalNumber(this)" />
        </p>
    </div> <!-- .modal-body -->
    <div class="modal-footer">
        <input type="hidden" id="bandwidth-expire-time">
        <a href="javascript:void(0);" class="btn" data-dismiss="modal">{{ _("Close") }}</a>
        <button class="btn btn-primary">{{ _("Transfer") }}</button>
    </div> <!-- .modal-footer -->
</div> <!-- #transfer-bandwidth-modal -->

<!-- Java Script -->
<script type="text/javascript">
    title('X-Tunnel');
</script>
<script type="text/javascript">
    $(function() {
        window.timer  = $.timer(function() {
            getUserInfo(0);
        });

        window.timer.set({
            time: 10000,
            autostart: false
        });

        getUserInfo(0);
    });
</script>
<script type="text/javascript">
    $('#info').dblclick(function(){
        // force update info from server
        // when double click info page
        getUserInfo(1);
    });
</script>
<!-- Summary -->
<script type="text/javascript">
    $('#register-trigger').click(function() {
        $('#login-form').addClass('hide');
        $('#register-form').removeClass('hide');
    });
</script>
<script type="text/javascript">
    $('#login-trigger').click(function() {
        $('#register-form').addClass('hide');
        $('#login-form').removeClass('hide');
    });
</script>
<script type="text/javascript">
    function getUserInfo(force) {
        var url = '/module/x_tunnel/control/info';
        if ( force ) {
            url = url + "?force=1";
        }
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'JSON',
            success: function(result) {
                if( result['res'] == 'logout' ){
                    tipClose();
                    return;
                }else if( result['res'] != 'success' ){
                    if( result['reason'] == "status:'UNKNOWN'" || result['reason'] == "status:False" ){
                        tip('{{ _("Connect to server fail, check GAE first.") }}', 'warning', false);
                        $('#login-form').addClass('hide');
                        $('#account-information').removeClass('hide');
                        $('#login-account').html(result['login_account']);
                        $('.login-account').val(result['login_account']);
                        return;
                    }else{
                        tip('Get Fail:' + result['reason'], 'warning', false);
                        return;
                    }
                } else {
                    tipClose();
                }
                getAvailableBandwidth(result['quota_list']);

                //getBillingHistory();
                // not imp yet

                window.timer.play();

                $('.nav-tabs > li').removeClass('hide');
                $('#login-form').addClass('hide');
                $('#account-information').removeClass('hide');

                $('#login-account').html(result['login_account']);
                $('.login-account').val(result['login_account']);
                $('#credit').html(getCreditForHumanReading(result['balance']));
                $('#bandwidth').html(getBandwidthForHumanReading(result['quota']));
            }
        });
    }
</script>
<script type="text/javascript">
    function getAvailableBandwidth(bandwidthList) {
        $('#available-bandwidth tbody').empty();

        if ( bandwidthList['current'] ) {
            displayBandwidth(bandwidthList['current']);
        }
        if ( bandwidthList['backup'] ) {
            bandwidthList['backup'].forEach(function(entry) {
                displayBandwidth(entry);
            });
        }

        $('#no-bandwidth').addClass('hide');
        $('#available-bandwidth').removeClass('hide');
    }
</script>
<script type="text/javascript">
    function displayBandwidth(bandwidthRecord) {
        var expireTime          = bandwidthRecord['end_time'],
            expireTimeObj       = new Date(expireTime * 1000);
            expireTimeString    = expireTimeObj.toISOString().substring(0, 10);
            bandwidth           = getBandwidthForHumanReading(bandwidthRecord['quota']);

        $('#available-bandwidth tbody').append('<tr><td><span class="expire-time" data-value="%s">%s</span></td><td><span class="bandwidth">%s</span> <a href="javascript:void(0);" class="transfer">[{{ _("Transfer") }}]</a></td></tr>'.format(expireTime, expireTimeString, bandwidth));
    }
</script>
<script type="text/javascript">
    function getCreditForHumanReading(credit) {
        if ( parseFloat(credit) == 0 ) {
            $('#transfer-credit-trigger').addClass('hide');
        }else{
            $('#transfer-credit-trigger').removeClass('hide');
        }
        return '$ ' + parseFloat(credit).toFixed(2);
    }
</script>
<script type="text/javascript">
    function getBandwidthForHumanReading(bandwidth) {
        var base        = 1000,
            bandwidth   = Math.round(bandwidth) / base / base;

        if ( bandwidth > base ) {
            bandwidth = bandwidth / base;
            bandwidth = parseFloat(bandwidth).toFixed(2) + ' GB';
        } else {
            bandwidth = parseFloat(bandwidth).toFixed(2) + ' MB';
        }
        return bandwidth;
    }
</script>
<script type="text/javascript">
    function isEmailLegal(email) {
        var regx = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return regx.test(email);
    }
</script>
<script type="text/javascript">
    function onLoginSubmit() {
        var username = $('#login-username').val(),
            password = $('#login-password').val();

        if ( !isEmailLegal(username) ) {
            tip('{{ _("Email seems invalid." )}}', 'error', false);
            return;
        } else if ( password.length < 6 ) {
            tip('{{ _("Password needs at least 6 charactors.") }}', 'error', false);
            return;
        }

        $('button[type=submit]', '#login-form').html('{{ _("Please wait...") }}');
        $('button[type=submit]', '#login-form').attr('disabled', 'disabled');
        return doLoginAction(username, password);
    }
</script>
<script type="text/javascript">
    function doLoginAction(username, password) {
        var postData = {
            'username': username, 
            'password': password,
            'is_register': 0
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/login',
            data: postData,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    window.location.reload();
                } else {
                    if( result['reason'] == "status:'UNKNOWN'" || result['reason'] == "status:False" ){
                        tip('{{ _("Connect to server fail, check GAE first.") }}', 'warning', false);
                    }else if ( result['reason'] == "auth fail" ){
                        tip('{{ _("Incorrect Email or password.") }}', 'error', false);
                    }else{
                        tip('Login fail:' + result['reason'], 'error', false);
                    }

                    $('button[type=submit]', '#login-form').html('{{ _("Login") }}');
                    $('button[type=submit]', '#login-form').removeAttr('disabled');
                }
            }
        });
    }
</script>
<script type="text/javascript">
    function onRegisterSubmit() {
        var username = $('#register-username').val(),
            password = $('#register-password').val();

        if ( !isEmailLegal(username) ) {
            tip('{{ _("Email seems invalid." )}}', 'error', false);
            return;
        } else if ( password.length < 6 ) {
            tip('{{ _("Password needs at least 6 charactors.") }}', 'error', false);
            return;
        }

        $('button[type=submit]', '#register-form').html('{{ _("Please wait...") }}');
        $('button[type=submit]', '#register-form').attr('disabled', 'disabled');
        return doRegisterAction(username, password);
    }
</script>
<script type="text/javascript">
    function doRegisterAction(username, password) {
        var postData = {
            'username': username, 
            'password': password,
            'is_register': 1
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/register',
            data: postData,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    return doLoginAction(username, password);
                } else {
                    if ( result['reason'] == 'user exist' ) {
                        tip('{{ _("Email has been taken by another user.") }}', 'error', false);
                    } else {
                        tip('{{ _("Unknown error occurred.") }}', 'error', false);
                    }

                    $('button[type=submit]', '#register-form').html('{{ _("Register") }}');
                    $('button[type=submit]', '#register-form').removeAttr('disabled');
                }
            }
        });
    }
</script>
<script type="text/javascript">
    $('#logout-trigger').click(function() {
        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/logout',
            dataType: 'JSON',
            success: function(result) {
                window.timer.stop();
                $('ul.nav-tabs > li').not(':first').addClass('hide');
                $('#account-information').addClass('hide');
                $('#login-form').removeClass('hide');

                // Fix bugs in Firefox
                $('button[type=submit]').removeAttr('disabled');
            },
            error: function(result) {
                tip('{{ _("Failed to log out.") }}', false);   
            }
        });
    });
</script>
<script type="text/javascript">
    $('#charge-trigger').click(function() {
        $('.alert-warning', '#charge-modal').addClass('hide');
        $('#charge-modal').modal();
    });
</script>
<script type="text/javascript">
    $('.btn-primary', '#charge-modal').click(function() {
        $(this).attr('disabled', 'disabled');
        $(this).html('{{ _("Please refresh page") }}');

        $('#charge-modal').submit();
    });
</script>
<script type="text/javascript">
    $('#transfer-credit-trigger').click(function() {
        $('.alert', '#transfer-credit-modal').addClass('hide');
        $('#transfer-credit-modal').modal();
    });
</script>
<script type="text/javascript">
    $('.btn-primary', '#transfer-credit-modal').click(function() {
        var transferAccount = $('#transfer-credit-username').val(),
            transferAmount  = $('#transfer-credit-amount').val();

        if ( !isEmailLegal(transferAccount) ) {
            $('.alert', '#transfer-credit-modal').html('{{ _("Transfer username seems not a valid Email address.") }}');
            $('.alert', '#transfer-credit-modal').removeClass('hide');
            return;
        }

        $('.btn-primary', '#transfer-credit-modal').attr('disabled', 'disabled');
        $('.btn-primary', '#transfer-credit-modal').html('{{ _("Please wait...") }}');
        return doTransferCreditAction(transferAccount, transferAmount);
    });
</script>
<script type="text/javascript">
    function doTransferCreditAction(transferAccount, transferAmount) {
        var postData = {
            'to_account': transferAccount,
            'amount': transferAmount,
            'transfer_type': 'balance'
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/transfer',
            data: postData,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    getUserInfo(1);
                    window.location.reload();
                } else {
                    $('.alert', '#transfer-credit-modal').html('{{ _("Error occurred: ") }}' + result['reason']);
                    $('.alert', '#transfer-credit-modal').removeClass('hide');
                }
                $('.btn-primary', '#transfer-credit-modal').removeAttr('disabled', 'disabled');
                $('.btn-primary', '#transfer-credit-modal').html('{{ _("Transfer") }}');
            }
        });
    }
</script>
<script type="text/javascript">
    $('#available-bandwidth').delegate('a.transfer', 'click', function() {
        var maxAvailableBandwidth = $('.bandwidth', $(this).parent()).html(),
            expireTime            = $('.expire-time', $(this).parent().parent()).attr('data-value');

        $('.alert', '#transfer-bandwidth-modal').addClass('hide');
        $('#transfer-bandwidth-amount').attr('placeholder', '{{ _("Max Available Bandwidth: ") }}' + maxAvailableBandwidth);
        $('#bandwidth-expire-time').val(expireTime);

        $('#transfer-bandwidth-modal').modal();
    });
</script>
<script type="text/javascript">
    $('.btn-primary', '#transfer-bandwidth-modal').click(function() {
        var transferAccount = $('#transfer-bandwidth-username').val(),
            transferAmount  = $('#transfer-bandwidth-amount').val(),
            expireTime      = $('#bandwidth-expire-time').val();

        if ( !isEmailLegal(transferAccount) ) {
            $('.alert', '#transfer-bandwidth-modal').html('{{ _("Transfer username seems not a valid Email address.") }}');
            $('.alert', '#transfer-bandwidth-modal').removeClass('hide');
            return;
        }

        $('.btn-primary', '#transfer-bandwidth-modal').attr('disabled', 'disabled');
        $('.btn-primary', '#transfer-bandwidth-modal').html('{{ _("Please wait...") }}');
        return doTransferBandwidthAction(transferAccount, transferAmount, expireTime);
    });
</script>
<script type="text/javascript">
    function parseUnit(str) {
        var out = [ 0, '' ]

        str = String(str)
        var num = parseFloat(str, 10)
        out[0] = num
        out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || ''
        return out
    }

    function doTransferBandwidthAction(transferAccount, transferAmount, expireTime) {
        var amountUnit = parseUnit(transferAmount)
        if ( amountUnit[1].toUpperCase() == "G" ){
            var amount = amountUnit[0] * 1000 * 1000 * 1000;
        } else {
            var amount = amountUnit[0] * 1000 * 1000;
        }
        var postData = {
            'to_account': transferAccount,
            'amount': amount,
            'end_time': expireTime,
            'transfer_type': 'quota'
        };

        $.ajax({
            type: 'POST',
            url: '/module/x_tunnel/control/transfer',
            data: postData,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    getUserInfo(1);
                    window.location.reload();
                } else {
                    $('.alert', '#transfer-bandwidth-modal').html('{{ _("Error occurred: ") }}' + result['reason']);
                    $('.alert', '#transfer-bandwidth-modal').removeClass('hide');
                }
                $('.btn-primary', '#transfer-bandwidth-modal').removeAttr('disabled', 'disabled');
                $('.btn-primary', '#transfer-bandwidth-modal').html('{{ _("Transfer") }}');
            }
        });
    }
</script>
<script type="text/javascript">
    function isDecimalNumber(obj) {
        var amountUnit = parseUnit(obj.value)
        if ( isNaN(amountUnit[0]) ) {
            obj.value = '';
            return;
        }
        if ( amountUnit[1].toUpperCase() != "G" && amountUnit[1].toUpperCase() != "M" && amountUnit[1] != "" ){
            alert('{{ _("Unit should be M or G.") }}');
            return;
        }
        if ( obj != null ) {
            if ( amountUnit[0].toString().split('.').length > 1 &&
                   amountUnit[0].toString().split(".")[1].length > 2 ) {
                alert('{{ _("Transfer amount should not more than 2 decimal places.") }}');
            }
        }
    }
</script>
<!-- Plans -->
<script type="text/javascript">
    $('#quarterly-plan-trigger').click(function() {
        orderPlan('Quarterly', 'quarterly');
    });

    $('#yearly-plan-trigger').click(function() {
        orderPlan('Yearly', "yearly");
    });
</script>
<script type="text/javascript">
    function orderPlan(planName, planValue) {
        $.ajax({
            data: {
                'product': 'x_tunnel', 
                'plan': planValue
            },
            type: 'POST',
            url: '/module/x_tunnel/control/order',
            dataType: 'JSON',
            success: function(result) {
                if( result['res'] != 'success' ){
                    if ( result['reason'] == "balance not enough" ) {
                        $('#charge-plan', '#charge-modal').val(planName);
                        $('.alert-warning', '#charge-modal').removeClass('hide');

                        $('#charge-modal').modal();
                    } else {
                        tip('{{ _("Failed to order: ") }}' + result['reason'], 'warning', false);
                    }
                } else {
                    tip('{{ _("Order successfully complete.") }}', 'info', false);
                    setTimeout(function () {
                        getUserInfo(1);
                        setTimeout(function () {
                            window.location.reload();
                        }, 1 * 1000);
                    }, 3 * 1000);
                }
            }
        });
    }
</script>
<script type="text/javascript">
    function getBillingHistory() {
        // TODO
        // Reference: function getHistory()
        // 
        // $('#billing-history').removeClass('hide');
        // $('#no-billing-history').addClass('hide');
    }
</script>
<!-- History -->
<script type="text/javascript">
    $('#get-history-button').click(function() {
        getHistory();

        $('#get-history-button').attr('disabled', 'disabled');
        $('#get-history-button').html('Please wait...');
    });
</script>
<script type="text/javascript">
    function getHistory() {
        $('#history-list tbody').empty();

        $.ajax({
            type: 'GET',
            data: {
                'start': 1999999999, 
                'end': 0, 
                'limit': 1000
            },
            url: '/module/x_tunnel/control/get_history',
            dataType: 'JSON',
            success: function(result) {
                if( result['res'] != 'success' ){
                    tip('Get Fail:' + result['reason'], 'warning', false);
                } else {
                    tipClose();
                }

                result['history'].forEach(function(entry) {
                    displayHistory(entry[1]);
                });

                $('#get-history-button').html('{{ _("Get") }}');
                $('#get-history-button').removeAttr('disabled');
            }
        });
    }
</script>
<script type="text/javascript">
    function displayHistory(item){
        var timeString = item['time'];
        delete item['time']; 

        var message = '';
        for ( property in item ) {
            message += property + ':' + item[property]+'; ';
        }

        $('#history-list tbody').append('<tr><td>%s</td><td>%s</td></tr>'.format(timeString, message));
    }
</script>
